package org.example.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 读取配置文件中的数据库连接参数
 */
public class JDBCUtils {
    private static String url;
    private static String username;
    private static String password;
    private static String driverClassName;
    private static DruidDataSource dataSource;
    //静态代码块
    static {
        try {
            //获取类加载器，读取配置文件，返回字节输入流对象
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            //创建Properties对象 加载输入流中的数据
            Properties pro = new Properties(); //Hashtable的子类，具有map集合的特点，key和value均为字符串类型
            //加载输入流中的数据
            pro.load(is);
            //从pro集合中获取配置文件中定义的参数，赋值给数据库连接属性
            driverClassName = pro.getProperty("driveClassName");
            url = pro.getProperty("url");
            username = pro.getProperty("username");
            password = pro.getProperty("password");
            System.out.println("获取配置文件中的属性值："+driverClassName+"--"+url+"--"+username+"--"+password);
            Class.forName(driverClassName);
            //设置数据源参数
            dataSource = new DruidDataSource();
            dataSource.setDriverClassName(pro.getProperty("driveClassName"));
            dataSource.setUrl(pro.getProperty("url"));
            dataSource.setUsername(pro.getProperty("username"));
            dataSource.setPassword(pro.getProperty("password"));
//            dataSource.setInitialSize(5);
//            dataSource.setMaxActive(10);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    // 返回数据源对象
    public static DruidDataSource getDataSource(){
        return dataSource;
    }
    //通过数据源（连接池)对象，返回Connection对象
    public static Connection getConn() throws SQLException{
        return dataSource.getConnection();
    }
    //定义静态方法，创建对象并返回
    public static Connection getCon() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //关闭连接
    public static void close(ResultSet rs, PreparedStatement ps, Connection con) {
        try {
            if (rs != null) {
                rs.close();
            }
            if ((ps != null)) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        }catch (SQLException sql){
            System.out.println("关闭资源异常"+sql.getMessage());
        }

    }
}
